package looting;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import csv.CSVFormat;
import csv.ReadCSV;

public class LootItemLoader {
	private static LootItem[] ITEM_CACHE = null;

	public static String lookUpItemName(int id) {
		for (LootItem item : loadItemCache()) {
			if (item.getId() == id) {
				return item.getName();
			}
		}

		return null;
	}

	public static boolean isStackable(int id) {
		for (LootItem item : loadItemCache()) {
			if (item.getId() == id) {
				return item.isStackable();
			}
		}

		return false;
	}

	public static LootItem[] loadItemCache() {
		LootItem[] items = null;
		if (ITEM_CACHE != null) {
			items = ITEM_CACHE;
		} else {
			items = getLootItemsFromFile("config" + File.separator + "itemData.csv");
		}

		return items;
	}

	public static LootItem[] getLootItemsFromFile(String fileName) {
		List<LootItem> lootItems = new ArrayList<LootItem>();
		ReadCSV csvReader = new ReadCSV(fileName, false, CSVFormat.DECIMAL_POINT);

		while (csvReader.next()) {
			if (csvReader.getColumnCount() >= 2) {
				try {
					String name = csvReader.get(1);
					int id = Integer.parseInt(csvReader.get(0));
					int value = 0;
					boolean stackable = false;

					if (csvReader.getColumnCount() > 3) {
						value = Integer.parseInt(csvReader.get(2));
						stackable = csvReader.get(3).equalsIgnoreCase("true");
					}

					lootItems.add(LootItemFactory.createLootItem(name, id, value, stackable));
				} catch (NumberFormatException nfe) {
					nfe.fillInStackTrace();
				}
			}
		}

		return lootItems.toArray(new LootItem[lootItems.size()]);
	}

	public static LootItem[] getLootItemsFromStream(InputStream stream) {
		List<LootItem> lootItems = new ArrayList<LootItem>();
		ReadCSV csvReader = new ReadCSV(stream, false, CSVFormat.DECIMAL_POINT);

		while (csvReader.next()) {
			if (csvReader.getColumnCount() >= 2) {
				try {
					String name = csvReader.get(1);
					int id = Integer.parseInt(csvReader.get(0));
					int value = 0;
					boolean stackable = false;

					if (csvReader.getColumnCount() > 3) {
						value = Integer.parseInt(csvReader.get(2));
						stackable = csvReader.get(3).equalsIgnoreCase("true");
					}

					lootItems.add(LootItemFactory.createLootItem(name, id, value, stackable));
				} catch (NumberFormatException nfe) {
					nfe.fillInStackTrace();
				}
			}
		}

		return lootItems.toArray(new LootItem[lootItems.size()]);
	}
}
